<template>
  <div ref="containerRef" id="cesiumContainer"></div>
  <Movepanel />
</template>

<script setup>
import { ref, onMounted } from 'vue'
import * as Cesium from 'cesium';
import { LayerManager } from '@/maputils/LayerManager'
import Movepanel from '@/components/MovePanel/MovePanel.vue';
import { getCurrentInstance } from 'vue';

const { appContext } = getCurrentInstance();
const globalProperties = appContext.config.globalProperties

const containerRef = ref()
const sysConfig = window.sysConfig || {}
let layerManager;

onMounted(() => {
  initGlobe()
  initEvent()
})

function initEvent() {
  globalProperties.$mitt.on('layerSwitch', ({ data, checked }) => {
    layerManager.getLayerByIds(data.id)
  })
}

/**
 * 初始化三维球
 */
function initGlobe() {
  Cesium.Ion.defaultAccessToken = sysConfig.cesiumToken || '';
  const extent = sysConfig.extent || [75.0, 0.0, 140.0, 60.0]
  Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(extent[0], extent[1], extent[2], extent[3])

  const viewerOption = sysConfig.viewerOpt || {}
  viewerOption.imageryProvider = new Cesium.TileMapServiceImageryProvider({
    url: Cesium.buildModuleUrl("Assets/Textures/NaturalEarthII")
  })
  let viewer;
  try {
    viewer = new Cesium.Viewer(containerRef.value, viewerOption)
    viewer._cesiumWidget._creditContainer.style.display = "none";
    // layerManager.viewer = viewer
    layerManager = new LayerManager(viewer)
    //挂载layerManager到全局实例上
    globalProperties.$layerManger = layerManager
    window.viewer = viewer;
    // 添加基础图层
    initBaseLayer()
    // // 添加地形服务
    layerManager.initTerrain(viewer, sysConfig.terrain)

    // initThematicLayer()

    // init3dtiles(viewer)
  } catch (error) {
    console.log(error);
  }
  // Add basic drag and drop functionality
  viewer.extend(Cesium.viewerDragDropMixin);

  // Show a pop-up alert if we encounter an error when processing a dropped file
  viewer.dropError.addEventListener(function (dropHandler, name, error) {
    console.log(error);
    window.alert(error);
  });
}


/**
 * 添加基础图层
 */
async function initBaseLayer() {
  const layerConfig = sysConfig.baseLayers;
  layerConfig.forEach((layerItem) => {
    if (layerItem.visible != false) {
      const type = layerItem.type;
      layerManager.addLayerByType(type, layerItem);
    }
  })

}

/**
 * 添加3dtiles
 */
function init3dtiles(viewer) {
  const tileset = new Cesium.Cesium3DTileset({
    url: "http://192.168.181.37/hdf/tds/mapdata/3dtiles/qx-simiao/tileset.json",
    // url: "https://data1.mars3d.cn/3dtiles/qx-simiao/tileset.json",
    show: true,
  });
  tileset.readyPromise.then((data) => {
    viewer.scene.primitives.add(data);
    // viewer.scene.globe.depthTestAgainstTerrain = true;
    viewer.zoomTo(tileset);
  })

}

/**
 * 添加业务图层
 */
function initThematicLayer() {

}


</script>

<style>
#cesiumContainer {
  width: 100vw;
  height: 100vh;
}

.cesium-viewer-toolbar {
  top: 60px;
}
</style>


